﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using LetsDoIt.BO;
using LetsDoIt.BO.ResponseMessages;
using LetsDoIt.Common;
using LetsDoIt.Interfaces;
using LetsDoIt.Localization;

namespace LetsDoIt.Forms
{
    public partial class UploadCasesForm : UserControl, INavigationForm
    {

        public string HasConnected { get; set; }
        private bool toCancel = false;
        private List<CaseInfo> listCases = new List<CaseInfo>();

        #region ctor
        public UploadCasesForm()
        {
            InitializeComponent();
        }

        public UploadCasesForm(MainForm hostForm, string identity)
        {
            HostForm = hostForm;
            Identity = identity;
            InitializeComponent();
        }
        #endregion ctor


        #region Implementation of INavigationForm

        public MainForm HostForm { get; set; }
        public string Identity { get; set; }
        public bool IsActive { get; set; }

        public void NavigationEnter(object sender)
        {
            //
            progressBarUploadEx.Visible = false;
            toCancel = false;
            //
            if (sender is IntroForm)
            {
                if (string.IsNullOrEmpty(HostForm.Settings.UserName) || string.IsNullOrEmpty(HostForm.Settings.Password))
                {
                    HostForm.NavigateTo(this, NavigationForms.FORM_USER_INFO);
                }
            }

            //
            listCases = WastesLocalFactory.LoadLocalCases();
            listCases.Reverse();//oldest first, newest last
            //
            lblUplodaCasesSummary.Text = string.Format(
                ResourceManager.Instance.GetString(@"MainForm_lblUplodaCasesSummary_Progress"),
                listCases.Count);
            btnUploadCases.Enabled = listCases.Count > 0;
        }

        public void NavigationLeave()
        {
            //
            toCancel = true;
        }

        #endregion


        #region events

        private void btnBack_Click(object sender, EventArgs e)
        {
            HostForm.NavigateBack(this, string.Empty);
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            //upload to web service
            int index = 0;
            int count = listCases.Count;
            btnUploadCases.Enabled = false;
            progressBarUploadEx.Visible = true;
            progressBarUploadEx.Value = 0;
            progressBarUploadEx.Text = ResourceManager.Instance.GetString(@"MainForm_ProgressBar_StartCounting");
            Application.DoEvents();
            //
            int totalFiles = 0;
            foreach (CaseInfo item in listCases)
            {
                if (item.Pictures != null)
                    totalFiles += item.Pictures.Count;
            }
            progressBarUploadEx.MaxValue = listCases.Count + totalFiles;
            //
            progressBarUploadEx.Text = ResourceManager.Instance.GetString(@"MainForm_ProgressBar_Connecting");
            Application.DoEvents();
            //
            if (string.IsNullOrEmpty(AuthServiceFactory.GetInstallationId()))
            {
                progressBarUploadEx.Text = ResourceManager.Instance.GetString(@"DialogWebConnectError");
                Application.DoEvents();
                //
                MessageBox.Show(
                    ResourceManager.Instance.GetString(@"DialogWebConnectError"),
                    ResourceManager.Instance.GetString(@"DialogErrorTitle"),
                    MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
            }
            else
            {
                string username = HostForm.Settings.UserName;
                string salt = AuthServiceFactory.GetUserSalt(username);
                string md5pass = Utils.Utils.GetPassHash(HostForm.Settings.Password + salt);
                if (AuthServiceFactory.ValidateUser(username, md5pass))
                {
                    int countProgress = 0;
                    foreach (CaseInfo caseInfo in listCases)
                    {
                        if (toCancel)
                        {
                            break;
                        }
                        {
                            index++;
                            progressBarUploadEx.Text = string.Format(
                                ResourceManager.Instance.GetString(@"MainForm_ProgressBarText"),
                                index, count);
                            countProgress++;
                            progressBarUploadEx.Value = countProgress;
                            Application.DoEvents();
                            //
                            bool isCaseUploadError = false;
                            ResponseWaste responseWaste = WastesServiceFactory.UploadCase(caseInfo, username, md5pass, HostForm.Settings.UploadDataAsTest);
                            if (responseWaste == null || !responseWaste.Succes)
                            {
                                //fail
                                if (
                                    MessageBox.Show(
                                        string.Format(ResourceManager.Instance.GetString(@"DialogUploadErrorAbort"), caseInfo.ID),
                                        ResourceManager.Instance.GetString(@"DialogErrorTitle"),
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) ==
                                    DialogResult.Yes)
                                {
                                    break;
                                }
                            }
                            else
                            {
                                //succes - continue with pictures
                                if (caseInfo.Pictures != null)
                                {
                                    bool exitFromPictureUpload = false;
                                    List<string> lstToUpload = new List<string>(caseInfo.Pictures);
                                    lstToUpload.Reverse();
                                    foreach (string picture in lstToUpload)
                                    {
                                        countProgress++;
                                        progressBarUploadEx.Value = countProgress;
                                        Application.DoEvents();
                                        //
                                        string pictureFile = Path.Combine(WastesLocalFactory.CasesStorePath(), picture);
                                        if (File.Exists(pictureFile))
                                        {
                                            ResponseImage responseImage = WastesServiceFactory.UploadImage(pictureFile, responseWaste.ServerID, username, md5pass);
                                            if (responseImage == null || !responseImage.Succes)
                                            {
                                                isCaseUploadError = true;
                                                if (MessageBox.Show(
                                                        string.Format(ResourceManager.Instance.GetString(@"DialogUploadImageErrorAbort"), caseInfo.ID),
                                                        ResourceManager.Instance.GetString(@"DialogErrorTitle"),
                                                        MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) ==
                                                    DialogResult.Yes)
                                                {
                                                    exitFromPictureUpload = true;
                                                    break;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            MessageBox.Show(string.Format(
                                                ResourceManager.Instance.GetString(@"DialogUploadErrorImageNotAvailable"),
                                                pictureFile));
                                        }
                                    }
                                    if (exitFromPictureUpload)
                                        break;
                                }

                                //cleanup
                                if (!isCaseUploadError)
                                {
                                    //delete the case file and pictures from file system
                                    WastesLocalFactory.DeleteLocalCase(caseInfo.ID);
                                }
                            }

                        }
                    }
                }
                else
                {
                    //user credentials invalid
                    MessageBox.Show(
                        ResourceManager.Instance.GetString(@"DialogLoginInvalidError"),
                        ResourceManager.Instance.GetString(@"DialogErrorTitle"),
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    HostForm.NavigateTo(this, NavigationForms.FORM_USER_INFO);
                }
                //
                progressBarUploadEx.Text = ResourceManager.Instance.GetString(@"DialogUploadCompleted");
                btnUploadCases.Enabled = false;
                Application.DoEvents();
            }
        }

        #endregion events

    }
}
